import { Image, message, Upload, UploadProps } from 'antd';
import { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import ImgCrop from 'antd-img-crop';
import { request } from '../../../utils/request';

interface ImageUploadProps {
  valueProps?: any,
  onChange: (e: any) => void;
  disabled?: boolean;
  delTip?: string, //删除图片文案
  listType?: 'text' | 'picture-card'
}

interface modalProps extends React.FC<ImageUploadProps> {

}

export const UploadImg: modalProps = ({
                                        valueProps,
                                        onChange,
                                        disabled = false,
                                        delTip = '确定删除已上传的图片',
                                        listType = 'text'
                                      }) => {
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      setLoading(false);
      const data = info.file.response;
      if (data.code === '1') {
        setFileList(info.fileList.map(file => {
          if (file.response) {
            file.url = file.response?.data?.url;
            file.name = file.response?.data?.fileName;
          }
          return file;
        }));
        triggerChange(info.fileList);
        message.success('上传成功');
        return;
      }
      message.error(data.desc);
    }
  };

  const triggerChange = (changedValue: any) => {
    onChange(changedValue);
  };

  const onPreview = (file) => {
    const url = file.url;
    setPreviewOpen(true);
    setPreviewImage(url);
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );
  return (
    <div className={styles.container}>
      <ImgCrop rotationSlider>
        <Upload
          name="file"
          method={'post'}
          action={'http://127.0.0.1:3000/api/admin/upload'}
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={true}
          maxCount={5}
          onChange={handleChange}
          onPreview={onPreview}
          headers={{ clientType: 'web', Authorization: `Bearer ${localStorage.getItem('token')}` }}
          onRemove={async (file) => {
            console.log(file)
            const res = await request('/admin/delete_asset', {
              method: 'post',
              data: { fileName: file.name },
              pureData: false
            });
            if (res?.code === '1') {
              message.success('删除成功');
              setFileList(fileList.filter(item => item.uid !== file.uid));
              triggerChange(fileList.filter(item => item.uid !== file.uid));
              return true;
            }
            message.error(res.desc);
            return false;
          }}
        >
          {
            fileList.length < 5 ? uploadButton : null
          }
        </Upload>
      </ImgCrop>
      {
        previewOpen &&
        <Image
          wrapperStyle={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => {
              if (!visible) {
                setPreviewImage('');
              }
              setPreviewOpen(visible);
            }
          }}
          src={previewImage}
        />
      }
    </div>
  );
};